package com.etogc.groupchat.group.frgm;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.etogc.dialog.InputCodeDialog;
import com.etogc.flycobanner.SimpleImageBanner;
import com.etogc.flycobanner.widget.Banner.base.BaseBanner;
import com.etogc.groupchat.R;
import com.etogc.groupchat.base.BaseFragment;
import com.etogc.groupchat.bean.AllGroupBean;
import com.etogc.groupchat.bean.MessageEvent;
import com.etogc.groupchat.common.WebActivity;
import com.etogc.groupchat.group.adpt.AllGroupAdapter;
import com.etogc.groupchat.group.biz.GroupHttpBiz2;
import com.etogc.http.ReqCons;
import com.etogc.http.ReqDataHandler;
import com.etogc.http.ReqErrorHandler;
import com.etogc.http.VolleyHttpUtil;
import com.etogc.view.LoadDialog;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import io.rong.imkit.RongIM;

/**
 * 全部群组
 * Created by ZeroVoid on 2018-3-22.
 */

public class AllGroupFragment extends BaseFragment {

    private SimpleImageBanner mBanner;
    private List<HashMap<String, String>> mBannerList;
    private PtrClassicFrameLayout ptrFragment;
    private RecyclerView mRecyclerView;
    private AllGroupAdapter allGroupAdapter;
    private View mHeadView;
    private List<AllGroupBean.AllGroup> allGroupBeans;
    private int pageIndex = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frgm_all_group, container, false);
        initBanner(view);
        requestBannerList();
        requestGroupList(pageIndex);
        EventBus.getDefault().register(this);
        return view;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    private void initBanner(View view) {
        ptrFragment = view.findViewById(R.id.ptr_fragment);
        mRecyclerView = view.findViewById(R.id.recycler_view);
        mHeadView = View.inflate(getActivity(), R.layout.group_head, null);
        mBanner = mHeadView.findViewById(R.id.banner);
        mBannerList = new ArrayList<>();
        allGroupBeans = new ArrayList<>();
        allGroupAdapter = new AllGroupAdapter(R.layout.all_group_item, allGroupBeans);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setHasFixedSize(false);
        mRecyclerView.setAdapter(allGroupAdapter);
        //分页加载
        ptrFragment.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                pageIndex++;
                requestGroupList(pageIndex);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageIndex = 1;
                requestGroupList(pageIndex);
            }
        });

        addBannerListener();
        addListener();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent) {
        if (messageEvent.getMessage().equals("refresh")) {
            pageIndex = 1;
            requestGroupList(pageIndex);
        }
    }

    private void addBannerListener() {
        // 设置banner点击事件
        mBanner.setOnItemClickL(new BaseBanner.OnItemClickL() {
            @Override
            public void onItemClick(int position) {
                String url = mBannerList.get(position).get("url");
                if (url != null) {
                    Intent intent = new Intent(getActivity(), WebActivity.class);
                    intent.putExtra("url", url);
                    intent.putExtra("title", "轮播详情");
                    startActivity(intent);
                }
            }
        });
    }

    /**
     * 首页列表点击事件
     */
    private void addListener() {
        allGroupAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<AllGroupBean.AllGroup> allGroups = (List<AllGroupBean.AllGroup>) adapter.getData();
                AllGroupBean.AllGroup allGroup = allGroups.get(position);
                if (allGroup.getIs_join() == 0) {
                    new InputCodeDialog(getActivity(), allGroup).initDialog().show();
                } else {
                    RongIM.getInstance().startGroupChat(getActivity(), allGroup.getId(), allGroup.getGroup_name());
                }
            }
        });
    }

    private void requestBannerList() {
        GroupHttpBiz2.getBannerList(getActivity(), new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                LoadDialog.dismiss(getActivity());
                boolean isSuccess = ReqErrorHandler.getInstance().isSuccess(response);
                if (isSuccess) {
                    List<Object> list = ReqDataHandler.getList(response);
                    if (list != null && list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            HashMap<String, String> map = (HashMap<String, String>) list.get(i);
                            mBannerList.add(map);
                        }
                        mBanner.setSource(mBannerList).setDelay(2).startScroll();
                        allGroupAdapter.addHeaderView(mHeadView);
                    }
                }
            }
        });
    }

    private void requestGroupList(int pos) {
        GroupHttpBiz2.getAllGroup(getActivity(), pos, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                LoadDialog.dismiss(getActivity());
                Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
                AllGroupBean allGroupBean = gson.fromJson(response.toString(), AllGroupBean.class);
                if (errCode == ReqCons.RESULT_SUCCESS) {
                    AllGroupBean.AllGroupList data = allGroupBean.getData();
                    if (data.getCurrentPage() == 1) {
                        allGroupBeans.clear();
                        allGroupBeans.addAll(allGroupBean.getData().getGroupList());
                    } else if (pageIndex > data.getTotalPage()) {
                        ptrFragment.refreshComplete();
                        return;
                    } else {
                        allGroupBeans.addAll(allGroupBean.getData().getGroupList());
                    }
                    allGroupAdapter.notifyDataSetChanged();
                }
                ptrFragment.refreshComplete();
            }
        });
    }
}
